<script lang="ts" setup>
import {
  LikeFilled,
  LikeOutlined,
  DislikeFilled,
  DislikeOutlined,
} from '@ant-design/icons-vue'
import { EditFilled } from '@ant-design/icons-vue'
import { useUserStore } from '@/common/stores/modules/users-store'
import { message } from 'ant-design-vue'
import relativeTime from 'dayjs/plugin/relativeTime'
import type { Comment1 } from '@/common/types/user-type'
import dayjs from 'dayjs'
import UpdateLocale from 'dayjs/plugin/updateLocale'
import 'dayjs/locale/zh-cn' // 引入中文语言包
dayjs.extend(relativeTime) // 相对时间
dayjs.locale('zh-cn') // 设置 dayjs 的语言为中文
dayjs.extend(UpdateLocale)

const userStore = useUserStore()

// 控制弹窗显示状态
const isModalVisible = ref(false)
// 新内容的输入框值
const comments = ref<Comment1[]>([])
const submitting = ref<boolean>(false)
// 定义点赞和踩踏的状态常量
const LIKE_ACTION = 'liked'
const DISLIKE_ACTION = 'disliked'
// 控制回复框的索引
const showReplyIndex = ref(1)
// 控制回复框的显示隐藏
const showReply = ref(false)

// 顶层留言 数据渲染
const commentsList = ref<Comment1[]>([
  {
    id: 1,
    author: 'Han Solo',
    avatar: '/public/lijie.svg',
    likes: 333,
    dislikes: 5,
    content:
      'jym，有工作之后去卷学历的吗，大家是如何看待卷技术和学历的呢（现在好像普通人技术一般的没点学历都约不上面试了',
    datetime: dayjs().to(dayjs('2024-11-14')),
    replies: [],
  },
  {
    id: 2,
    author: 'Han Solo',
    avatar: '/public/github.svg',
    likes: 333,
    dislikes: 5,
    content:
      '程序猿转行干什么好呢 虽然公司待遇什么的都不错 但是真是干够了 没有一点意思',
    datetime: dayjs().to(dayjs('2024-11-13')),
    replies: [
      {
        id: 1,
        author: 'Luke Skywalker',
        likes: 0,
        dislikes: 0,
        avatar: '/public/lijie.svg',
        content: '要搭配视频食用',
        datetime: dayjs().to(dayjs('YYYY-MM-DD HH:mm:ss')),
      },
    ],
  },
  {
    id: 3,
    author: 'Han Solo',
    avatar: '/public/gitee.svg',
    likes: 333,
    dislikes: 5,
    content: '倒计时26分钟',
    datetime: dayjs().to(dayjs('2024-11-12')),
    replies: [],
  },
  {
    id: 4,
    author: 'Han Solo',
    avatar: '/public/weixin.svg',
    likes: 333,
    dislikes: 5,
    content:
      '有没有大佬了解ai，有没有适合在springboot里，纯cpu执行的向量化模型，用了word2vec感觉效果不太行',
    datetime: dayjs().to(dayjs('2024-11-12')),
    replies: [
      {
        id: 2,
        author: 'User C',
        likes: 0,
        dislikes: 0,
        avatar: '/avatar3.png',
        content: '了解个啥',
        datetime: '2024-10-03',
      },
    ],
  },
  {
    id: 5,
    author: 'Han Solo',
    avatar: '/public/lijie.svg',
    likes: 333,
    dislikes: 5,
    content: '有没有JYM推荐一款，入手无人机，适合自驾航拍那种就成',
    datetime: dayjs().to(dayjs('2024-11-11')),
    replies: [],
  },
  {
    id: 6,
    author: 'Han Solo',
    avatar: '/public/lijie.svg',
    likes: 333,
    dislikes: 5,
    content: '测试环境后台崩了，两个点了 ',
    datetime: dayjs().to(dayjs('2024-11-11')),
    replies: [],
  },
  {
    id: 7,
    author: 'Han Solo',
    avatar: '/public/lijie.svg',
    likes: 333,
    dislikes: 5,
    content: '公司的网慢死了，数据库半小时都没连上 ',
    datetime: dayjs().to(dayjs('2024-11-11')),
    replies: [],
  },
  {
    id: 8,
    author: 'Han Solo',
    avatar: '/public/lijie.svg',
    likes: 333,
    dislikes: 5,
    content:
      '眼镜妹真的反差，平时看着斯斯文文，可可爱爱的女孩子，点的歌全是蹦迪神曲 ',
    datetime: dayjs().to(dayjs('2024-11-11')),
    replies: [],
  },
  {
    id: 9,
    author: 'Han Solo',
    avatar: '/public/lijie.svg',
    likes: 333,
    dislikes: 5,
    content: 'JYM, 掘金的AI 刷题和 LeeCode 是一样的吗',
    datetime: dayjs().to(dayjs('2024-11-11')),
    replies: [],
  },
  {
    id: 10,
    author: 'Han Solo',
    avatar: '/public/lijie.svg',
    likes: 333,
    dislikes: 5,
    content: 'jym，摸鱼被辞退了，呜呜呜 ，可恶的掘金，一直忍不住点，呜呜呜',
    datetime: dayjs().to(dayjs('2024-11-11')),
    replies: [],
  },
  {
    id: 11,
    author: 'Han Solo',
    avatar: '/public/lijie.svg',
    likes: 333,
    dislikes: 5,
    content: '是啊！建国才70年，居然有这么多人敢背30年的房贷',
    datetime: dayjs().to(dayjs('2024-11-11')),
    replies: [],
  },
  {
    id: 12,
    author: 'Han Solo',
    avatar: '/public/lijie.svg',
    likes: 333,
    dislikes: 5,
    content: '不知不觉一周又要过去了，写了一周的sql拉数，代码量0。',
    datetime: dayjs().to(dayjs('2024-11-11')),
    replies: [],
  },
  {
    id: 13,
    author: 'Han Solo',
    avatar: '/public/lijie.svg',
    likes: 333,
    dislikes: 5,
    content: '有大佬知道最近北京的前端行情怎么样吗 本人两年前端 双非科班',
    datetime: dayjs().to(dayjs('2024-11-11')),
    replies: [],
  },
  {
    id: 14,
    author: 'Han Solo',
    avatar: '/public/lijie.svg',
    likes: 333,
    dislikes: 5,
    content:
      '我总是很擅长把一个可以花精力解决的问题，变成一个需要时间接受的事实。',
    datetime: dayjs().to(dayjs('2024-11-11')),
    replies: [],
  },
  {
    id: 15,
    author: 'Han Solo',
    avatar: '/public/lijie.svg',
    likes: 333,
    dislikes: 5,
    content: '有没有无界大佬，求教问题～',
    datetime: dayjs().to(dayjs('2024-11-11')),
    replies: [],
  },
])

// 显示弹窗
const showModal = () => {
  isModalVisible.value = true
}

// 发布内容
const handlePublish1 = (content: string) => {
  console.log('newContent:', content) // 调试输出

  if (content.trim()) {
    // 创建新的留言对象
    const newComment = {
      id: commentsList.value.length + 1, // 生成唯一的 id
      author: userStore.userInfo?.user, // 替换为实际用户名称
      avatar: '/public/lijie.svg', // 替换为实际头像路径
      likes: 0,
      dislikes: 0,
      content: content,
      datetime: dayjs().fromNow(), // 显示相对时间
      replies: [],
    }

    // 添加到顶级留言列表
    commentsList.value.unshift(newComment)
    // 将更新后的列表存储到 localStorage
    localStorage.setItem('commentsList', JSON.stringify(commentsList.value))

    message.success('发布成功！')
    isModalVisible.value = false // 关闭弹窗
  } else {
    message.warning('内容不能为空！')
  }
}

// 点击回复弹出输入框
const handlePublish = (index: number) => {
  // 先隐藏回复框，然后再设置新位置
  showReply.value = false

  // 等待 DOM 更新后再设置正确的回复框位置
  nextTick(() => {
    showReplyIndex.value = index
    showReply.value = true
    console.log(index, '你好')
  })
}

// 处理顶级留言回复提交
const handleReplySubmit = (reply: string) => {
  submitting.value = true

  // 找到对应的评论，添加回复
  const targetComment = commentsList.value.find(
    comment => comment.id === showReplyIndex.value,
  )
  if (targetComment) {
    setTimeout(() => {
      submitting.value = false
      const newReply = {
        id: targetComment.replies.length + 1,
        author:  userStore.userInfo?.user,
        avatar: '/public/lijie.svg',
        likes: 0,
        dislikes: 0,
        content: reply,
        datetime: dayjs().fromNow(),
      }

      // 检查 targetComment.replies 是否为数组
      if (Array.isArray(targetComment.replies)) {
        targetComment.replies = [...targetComment.replies, newReply]
      } else {
        // 如果 targetComment.replies 是 undefined，则初始化为数组并添加 newReply
        targetComment.replies = [newReply]
      }

      // 更新目标评论的 replies，确保它是响应式的
      commentsList.value = [...commentsList.value] // 强制视图更新

      // 保存到 localStorage
      localStorage.setItem('commentsList', JSON.stringify(commentsList.value))

      message.success('发送成功')
      showReply.value = false
    }, 200)
  }
}

// 处理点赞或踩踏操作的通用函数
const handleAction = (
  comment: any,
  actionType: string,
  countProperty: string,
) => {
  // 如果已经执行了该操作，则取消操作
  if (comment.action === actionType) {
    comment[countProperty] -= 1
    comment.action = ''
  } else {
    // 如果没有执行该操作，则执行操作
    comment[countProperty] += 1
    comment.action = actionType
  }
}

// 点赞事件
const like = (index: number) => {
  const comment = commentsList.value[index]
  handleAction(comment, LIKE_ACTION, 'likes')
}

// 踩踏事件
const dislike = (index: number) => {
  const comment = commentsList.value[index]
  handleAction(comment, DISLIKE_ACTION, 'dislikes')
}

// 从 localStorage 加载数据
onMounted(() => {
  const savedComments = localStorage.getItem('commentsList')
  if (savedComments) {
    commentsList.value = JSON.parse(savedComments)
  }
  // 升序排序：根据 datetime 字段升序排列
  commentsList.value.sort((a, b) =>
    dayjs(a.datetime).isBefore(dayjs(b.datetime)) ? -1 : 1,
  )
})
</script>

<template>
  <div class="coder-community">
    <!-- 发布内容按钮 -->
    <a-button
      class="coder-community-right-btn no-bl"
      type="primary"
      @click="showModal"
    >
      <EditFilled />
      发布内容
    </a-button>
    <div class="coder-community-left">
      <h3>技术问答</h3>
      <!-- 顶部留言 -->
      <a-comment v-for="(item, index) in commentsList" :key="index">
        <!-- 用户名 author-->
        <template #author>
          <a>{{ item.author }}</a>
        </template>
        <!-- 头像 avatar-->
        <template #avatar>
          <a-avatar :src="item.avatar" alt="Han Solo" />
        </template>
        <!-- 评论内容 content-->
        <template #content>
          <p>
            {{ item.content }}
          </p>
        </template>
        <!-- 发表时间 datetime-->
        <template #datetime>
          <a-tooltip :title="dayjs().format('YYYY-MM-DD HH:mm:ss')">
            <span>{{ item.datetime }}</span>
          </a-tooltip>
        </template>
        <!-- 点赞评论回复 actions-->
        <template #actions>
          <span key="comment-basic-like">
            <a-tooltip title="Like">
              <template v-if="item.action === 'liked'">
                <LikeFilled @click="like(index)" />
              </template>
              <template v-else>
                <LikeOutlined @click="like(index)" />
              </template>
            </a-tooltip>
            <span style="padding-left: 0.5rem; cursor: auto">
              {{ item.likes }}
            </span>
          </span>
          <span key="comment-basic-dislike">
            <a-tooltip title="Dislike">
              <template v-if="item.action === 'disliked'">
                <DislikeFilled @click="dislike(index)" />
              </template>
              <template v-else>
                <DislikeOutlined @click="dislike(index)" />
              </template>
            </a-tooltip>
            <span style="padding-left: 0.5rem; cursor: auto">
              {{ item.dislikes }}
            </span>
          </span>
          <span key="comment-nested-reply-to" @click="handlePublish(item.id)"
            >回复</span
          >
        </template>
        <!--  二级留言 -->
        <div
          v-if="item.replies && item.replies.length"
          class="educ-second-comment"
        >
          <educ-second-comment :comments="item.replies" />
        </div>

        <!-- 回复框 -->
        <div
          class="educ-reply-box"
          v-show="showReplyIndex === item.id && showReply"
        >
          <educ-reply-box @submitReply="handleReplySubmit" />
        </div>
      </a-comment>
    </div>

    <!-- 右侧  -->
    <div class="coder-community-right">
      <!-- 发布内容按钮 -->
      <a-button
        class="coder-community-right-btn"
        type="primary"
        style="width: 100%"
        @click="showModal"
      >
        <EditFilled />
        发布内容
      </a-button>

      <!-- 自定义弹窗组件 -->
      <educ-custom-amodal
        :visible="isModalVisible"
        @update:visible="isModalVisible = $event"
        @submit="handlePublish1"
      />
      <!-- 本周热榜 -->
      <educ-dynamic-hot-list />
      <!-- 热门话题 -->
      <educ-dynamic-hot-topic />
    </div>
  </div>
</template>

<style lang="scss" scoped>
.coder-community {
  .no-bl {
    display: none;
  }

  display: flex;

  &-left {
    width: 70%;
    padding: 1.875rem;
    margin: 0 2.5rem;
    background-color: $educ-color-white;
    border-radius: 0.3125rem;
  }

  &-right {
    width: 30%;

    &-btn {
      width: 100%;
      height: 3.125rem;
      margin-bottom: 1.25rem;
      background-color: $educ-color-primary;
      border: none;
      border-radius: 0.5rem;
      outline: none;
    }
  }
}

@media screen and (width <= 48rem) {
  .coder-community {
    display: block;

    .no-bl {
      display: block;
      width: 50%;
      margin: 0.625rem auto;
    }

    .coder-community-left {
      width: 90%;
      margin: auto;
    }

    .coder-community-right {
      display: none;
    }
  }
}
</style>
